package com.example.timetable.fragment;

import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.timetable.adapter.LessonAdapter;
import com.example.timetable.dao.Course;
import com.example.timetable.databinding.FragmentCourseBinding;

import java.util.List;

/**
 * 添加编辑课程内容的碎片
 */
public class CourseFragment extends Fragment {

    private FragmentCourseBinding binding;
    private Course course;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentCourseBinding.inflate(inflater, container, false);
        showLessonInfo();
        showCourseInfo();
        return binding.getRoot();
    }

    /**
     * 显示课程信息
     */
    private void showCourseInfo() {
        binding.tvCourseName.setText(course.getCourseName());
        binding.etCourseName.setText(course.getCourseName());
        binding.etTeacherName.setText(course.getTeacherName());
        binding.etStartWeek.setText(String.valueOf(course.getStartWeek()));
        binding.etEndWeek.setText(String.valueOf(course.getEndWeek()));
    }

    /**
     * 显示课次信息
     */
    private void showLessonInfo() {
        List<Course> courseList = course.toDetail();
        if (courseList == null) {
            return;
        }
        LessonAdapter adapter = new LessonAdapter(getContext(), courseList, new DeleteListener());
        binding.lvLesson.setAdapter(adapter);
    }


    private class DeleteListener implements LessonAdapter.ClickListener {
        @Override
        public void onClick(Course course) {
            new AlertDialog.Builder(getContext())
                    .setTitle("删除课次")
                    .setPositiveButton("确定删除", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            course.delete();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create()
                    .show();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}